package com.example.userprovider.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Map;

/**
 * JWT 生成工具类
 * @author
 * @date 2021-4-18 21:55
 */
public class JwtGeneratorUtils {

    private static String SECRET_KEY = "secret-key";

    private static Key getKeyInstance(){
        SignatureAlgorithm signatureAlgorithm  = SignatureAlgorithm.HS256;
        byte[] keySecretByte = DatatypeConverter.parseBase64Binary(SECRET_KEY);
        Key key = new SecretKeySpec(keySecretByte,signatureAlgorithm.getJcaName());
        return key;
    }

    /**
     * 生成token
     * @param payload
     * @return
     */
    public static String generateToken(Map<String,Object> payload) {
        ObjectMapper objectMapper = new ObjectMapper();
        String token = null;
        try {
            token = Jwts.builder().setPayload(objectMapper.writeValueAsString(payload)).
                    signWith(SignatureAlgorithm.HS256,getKeyInstance()).compact();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
        return claimsJws.getBody();
    }
}
